package core

import (
	"fmt"
	"time"

	"github.com/gomodule/redigo/redis"
)

const (
	redisTemplate = "%s:%d"
)

type RedisParam struct {
	Host string `json:"host" toml:"host"`
	Port int    `json:"port" toml:"port"`
	Pwd  string `json:"pwd" toml:"pwd"`
	DB   string `json:"db" toml:"db"`
}

func (redisParam *RedisParam) New() *redis.Pool {
	return &redis.Pool{
		MaxActive:   64,
		MaxIdle:     32,
		IdleTimeout: 60 * time.Second,
		Dial: func() (redis.Conn, error) {
			conn, err := redis.Dial("tcp", redisParam.getAddress())
			if err != nil {
				return nil, err
			}
			if redisParam.Pwd != "" {
				if _, err := conn.Do("AUTH", redisParam.Pwd); err != nil {
					_ = conn.Close()
					return nil, err
				}
				if _, err := conn.Do("SELECT", redisParam.DB); err != nil {
					_ = conn.Close()
					return nil, err
				}
			}
			return conn, err
		},
	}
}

func (redisParam *RedisParam) getAddress() string {
	return fmt.Sprintf(redisTemplate, redisParam.Host, redisParam.Port)
}
